package com.heima.store;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class RedisChatMemoryStore implements ChatMemoryStore {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public List<ChatMessage> getMessages(Object memoryId) {
        String json = stringRedisTemplate.opsForValue().get(memoryId.toString());
        if (json == null) {
            return List.of(); // 如果没有找到对应的消息，返回空集合
        }
        // 将json数据转换成list
        List<ChatMessage> list = ChatMessageDeserializer.messagesFromJson(json);
        return list;
    }
    // 更新会话消息
    public void updateMessages(Object memoryId, List<ChatMessage> list) {
        //1.把list转换成json数据
        String json = ChatMessageSerializer.messagesToJson(list);
        //2.把json数据存储到redis中
        stringRedisTemplate.opsForValue().set(memoryId.toString(), json,1, TimeUnit.DAYS); // 设置过期时间为1天
    }
    public void deleteMessages(Object memoryId) {
        stringRedisTemplate.delete(memoryId.toString());
    }
}
